package com.hngy.xpq.canvas;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private ImageView bg;
    private TextView text_bg;
    private Bitmap alterBitmap;
    private double NX,NY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化
        init();
        // 图层初始化
        initImage();
    }

    private void initImage() {
        //资源解析
        Bitmap bitmap =
                BitmapFactory.decodeResource(getResources(),R.drawable.scratch_card);
        alterBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),bitmap.getConfig());
        //收集屏幕信息
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        //适应屏幕
        NX = bitmap.getWidth()/dm.widthPixels;
        NY = bitmap.getHeight()/dm.heightPixels;

        //创建一个canvas对象
        Canvas canvas = new Canvas(alterBitmap);
        //画笔
        Paint paint = new Paint();
        //设置颜色
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        //Matrix对象
        Matrix matrix = new Matrix();
        //画图
        canvas.drawBitmap(bitmap,matrix,paint);
        //监听
        bg.setOnTouchListener(new View.OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                try {
                    int x = (int)event.getX();
                    int y = (int)event.getY();
                    for (int i = -100 ; i<100 ; i++){
                        for (int j = -100 ; j<100 ; j++){
                            if (Math.sqrt((i*i) + (j*j)) <= 100){
                                alterBitmap.setPixel((int)(x*NX) + i , (int) (y*NY +90)+j , Color.TRANSPARENT);
                            }
                        }
                    }
                    bg.setImageBitmap(alterBitmap);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return true;
            }
        });
    }

    private void init() {
        bg = findViewById(R.id.image_bm);
        text_bg = findViewById(R.id.text_bg);

        //随机抽奖
        Random XingYun = new Random();
        int kelang = XingYun.nextInt(3);
        String[] deng = {"一等奖","二等奖","三等奖"};
        text_bg.setText(deng[kelang]);
    }


}